//
//  KTaskManage.m
//  Keping
//
//  Created by 柯平 on 2017/6/19.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KTaskManage.h"

@interface KTaskManage ()

@property (strong) NSMutableSet  *taskSets;

@end

@implementation KTaskManage

+(instancetype)sharedQueue
{
    static KTaskManage* __instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __instance = [[KTaskManage alloc] init];
    });
    return __instance;
}

-(instancetype)init
{
    self = [super init];
    if (self) {
        _taskSets = [[NSMutableSet alloc] init];
        _taskOperationQueue = [[NSOperationQueue alloc] init];
    }
    return self;
}

-(void)addTask:(KTask *)task
{
    @synchronized (self) {
        NSParameterAssert([task isKindOfClass:[KTask class]]);
        if (![self.taskSets containsObject:task]) {
            [self.taskSets addObject:task];
        }
    }
}

-(void)removeTask:(KTask *)task
{
    @synchronized (self) {
        NSParameterAssert([task isKindOfClass:[KTask class]]);
        if ([self.taskSets containsObject:task]) {
            [self.taskSets removeObject:task];
        }
    }
}

-(KTask *)containTask:(Class)taskName
{
    @synchronized (self) {
        __block KTask* task = nil;
        
        [self.taskSets enumerateObjectsUsingBlock:^(id  _Nonnull obj, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:taskName]) {
                task = obj;
                *stop = YES;
            }
        }];
        return task;
    }
}

-(KTask *)containTask:(Class)taskName observer:(id)observer
{
    @synchronized (self) {
        __block KTask* task = nil;
        [self.taskSets enumerateObjectsUsingBlock:^(id  _Nonnull obj, BOOL * _Nonnull stop) {
            if ([obj isKindOfClass:taskName] && [obj delegate] == observer) {
                task = obj;
                *stop = YES;
            }
        }];
        return task;
    }
}

-(NSSet *)tasksForObserver:(id)observer
{
    @synchronized (self) {
        NSMutableSet* taskSet = [[NSMutableSet alloc] init];
        
        [self.taskSets enumerateObjectsUsingBlock:^(id  _Nonnull obj, BOOL * _Nonnull stop) {
            if ([obj delegate] == observer) {
                [taskSet addObject:obj];
            }
        }];
        return [taskSet count] ? taskSet:nil;
    }
}

@end
